package com.lhczf.lucenedb.threads;

import com.lhczf.lucenedb.service.DataHub;
import com.lhczf.lucenedb.service.LuceneDbServer;

import com.lhczf.lucenedb.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.index.IndexWriter;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class MonitorThread implements Runnable {

    @Override
    public void run() {
        int tc = Thread.activeCount();
        Thread[] ts = new Thread[tc];
        Thread.enumerate(ts);
        DataHub dataHub = SpringUtil.getBean(DataHub.class);
        Map<String, Thread> threadMap = new HashMap<>(16);
        for (Thread thread : ts) {
            threadMap.put(thread.getName(), thread);
        }
        final LuceneDbServer server = SpringUtil.getBean(LuceneDbServer.class);
        Thread.currentThread().setName("lucenedb-thread-monitor");
		
        dataHub.getMonitorThreadsMapKeys().forEach(key -> {
            Object object = dataHub.getMonitorThreadsMap(key);
            Thread thread = threadMap.get(key);
            if (thread == null) {
                log.warn("{}线程已经退出。", key);
                if (key.indexOf("producer") != -1) {
                    server.startProducer((File) object, key);
                } else if (key.indexOf("consumer") != -1) {
                    server.startConsumerThread(key, (IndexWriter) object);
                } else {
                    server.startIntegrationIndexThread(key);
                }
            }
        });
    }
}
